<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仪表板查看 - AI数据分析助手</title>
    
    <!-- Bootstrap CSS -->
    <link href="./assets/bootstrap.min.css" rel="stylesheet">
    <!-- GridStack CSS -->
    <link rel="stylesheet" href="./assets/gridstack.min.css">
    <!-- Font Awesome -->
    <link href="./assets/fontawesome.min.css" rel="stylesheet">
    <!-- Plotly.js -->
    <script src="./assets/plotly-latest.min.js"></script>
    
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --accent-color: #f093fb;
            --success-color: #4facfe;
            --warning-color: #43e97b;
            --danger-color: #fa709a;
            --dark-color: #2c3e50;
            --light-color: #ecf0f1;
            --gradient-primary: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            --gradient-accent: linear-gradient(135deg, var(--accent-color) 0%, var(--success-color) 100%);
            --gradient-warm: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            --gradient-cool: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            --shadow-soft: 0 10px 30px rgba(0, 0, 0, 0.1);
            --shadow-medium: 0 15px 35px rgba(0, 0, 0, 0.15);
            --shadow-strong: 0 20px 40px rgba(0, 0, 0, 0.2);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--gradient-cool);
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-50px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        @keyframes shimmer {
            0% {
                background-position: -200px 0;
            }
            100% {
                background-position: calc(200px + 100%) 0;
            }
        }

        /* 顶部导航栏 */
        .navbar {
            background: var(--gradient-primary) !important;
            backdrop-filter: blur(10px);
            box-shadow: var(--shadow-medium);
            border: none;
            padding: 1rem 0;
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
            color: white !important;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .navbar-nav .nav-link {
            color: rgba(255, 255, 255, 0.9) !important;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 0 0.5rem;
            border-radius: 20px;
            padding: 0.5rem 1rem !important;
        }

        .navbar-nav .nav-link:hover {
            color: white !important;
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        /* 主容器 */
        .main-container {
            padding: 2rem 0;
            min-height: calc(100vh - 80px);
        }

        /* 仪表板选择器 */
        .dashboard-selector {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-soft);
            animation: fadeInUp 0.6s ease;
        }

        .dashboard-selector h2 {
            background: var(--gradient-primary);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-weight: 700;
            margin-bottom: 1.5rem;
            text-align: center;
        }

        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }

        .dashboard-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: var(--shadow-soft);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
            position: relative;
            overflow: hidden;
        }

        .dashboard-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -200px;
            width: 200px;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
            transition: left 0.5s;
        }

        .dashboard-card:hover::before {
            left: 100%;
        }

        .dashboard-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-medium);
            border-color: var(--primary-color);
        }

        .dashboard-card.active {
            border-color: var(--primary-color);
            background: var(--gradient-accent);
            color: white;
        }

        .dashboard-card h5 {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .dashboard-card .text-muted {
            opacity: 0.7;
        }

        /* 仪表板内容区域 */
        .dashboard-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 2rem;
            box-shadow: var(--shadow-soft);
            animation: fadeInUp 0.8s ease;
            min-height: 600px;
        }

        .dashboard-header {
            text-align: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--light-color);
        }

        .dashboard-title {
            background: var(--gradient-primary);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-weight: 700;
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
        }

        .dashboard-description {
            color: #6c757d;
            font-size: 1.1rem;
            font-style: italic;
        }

        /* 图表网格 - 使用GridStack布局 */
        .charts-grid {
            margin-top: 2rem;
        }
        
        .grid-stack {
            background: transparent;
        }
        
        .grid-stack-item-content {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            position: relative;
            box-sizing: border-box;
            height: 100%;
            width: 100%;
        }
        
        .grid-stack-item-content:hover {
            box-shadow: var(--shadow-medium);
        }
        
        .grid-stack-item-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient-primary);
        }

        .chart-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: var(--shadow-soft);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            animation: fadeInUp 0.6s ease;
        }

        .chart-card:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-medium);
        }

        .chart-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient-primary);
        }

        .chart-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 5px;
        }
        
        .chart-title-container {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 5px 10px;
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }

        .chart-container {
            height: calc(100% - 35px);
            position: relative;
            width: 100%;
            overflow: hidden !important;
        }
        
        .chart-container .js-plotly-plot {
            overflow: hidden !important;
        }
        
        .chart-container .plotly {
            overflow: hidden !important;
        }

        /* 加载动画 */
        .loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200px;
            color: var(--primary-color);
            padding: 2rem;
        }

        .loading .spinner-border {
            width: 3rem;
            height: 3rem;
            border-width: 0.3em;
            color: var(--primary-color);
        }

        .loading .loading-text {
            margin-top: 1rem;
            font-size: 1.1rem;
            font-weight: 500;
            color: var(--primary-color);
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            border: 2px dashed rgba(102, 126, 234, 0.3);
            margin: 2rem 0;
            box-shadow: var(--shadow-soft);
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1.5rem;
            color: var(--primary-color);
            opacity: 0.8;
        }

        .empty-state h4 {
            margin-bottom: 1rem;
            font-weight: 600;
            color: var(--dark-color);
        }

        .empty-state p {
            color: #6c757d;
            font-size: 1rem;
            margin-bottom: 1.5rem;
            line-height: 1.6;
        }

        /* 错误状态 */
        .error-state {
            text-align: center;
            padding: 3rem 2rem;
            background: rgba(255, 245, 245, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            border: 2px solid rgba(229, 62, 62, 0.3);
            margin: 2rem 0;
            box-shadow: var(--shadow-soft);
        }

        .error-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--danger-color);
        }

        .error-state h5 {
            color: #c53030;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .error-state p {
            color: #9b2c2c;
            margin-bottom: 1rem;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
            
            .charts-grid {
                grid-template-columns: 1fr;
            }
            
            .dashboard-title {
                font-size: 2rem;
            }
        }

        /* 工具提示 */
        .tooltip {
            position: relative;
        }

        .tooltip::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: var(--dark-color);
            color: white;
            padding: 0.5rem;
            border-radius: 5px;
            font-size: 0.8rem;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .tooltip:hover::after {
            opacity: 1;
            visibility: visible;
        }

        /* 编辑模式按钮 */
        .edit-mode-btn {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            background: var(--gradient-primary);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 1rem 1.5rem;
            font-weight: 600;
            box-shadow: var(--shadow-medium);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .edit-mode-btn:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-strong);
            color: white;
        }

        /* 全屏模式 */
        .fullscreen-chart {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: white;
            z-index: 9999;
            padding: 2rem;
        }

        .fullscreen-chart .close-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: var(--danger-color);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 1.2rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-chart-line me-2"></i>
                AI数据分析助手 - 仪表板查看
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/">
                    <i class="fas fa-home me-1"></i>
                    首页
                </a>
                <a class="nav-link" href="/dashboard.html">
                    <i class="fas fa-edit me-1"></i>
                    编辑模式
                </a>
            </div>
        </div>
    </nav>

    <div class="container main-container">
        <!-- 仪表板选择器 -->
        <div class="dashboard-selector">
            <h2><i class="fas fa-tachometer-alt me-2"></i>选择仪表板</h2>
            <div id="dashboardGrid" class="dashboard-grid">
                <div class="loading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <div>加载仪表板列表...</div>
                </div>
            </div>
        </div>

        <!-- 仪表板内容 -->
        <div id="dashboardContent" class="dashboard-content" style="display: none;">
            <div class="dashboard-header">
                <h1 id="dashboardTitle" class="dashboard-title">仪表板标题</h1>
                <p id="dashboardDescription" class="dashboard-description">仪表板描述</p>
            </div>
            
            <div id="chartsGrid" class="charts-grid">
                <!-- 图表将在这里动态加载 -->
            </div>
        </div>
    </div>

    <!-- 编辑模式按钮 -->
    <button class="edit-mode-btn tooltip" data-tooltip="切换到编辑模式" onclick="switchToEditMode()">
        <i class="fas fa-edit me-2"></i>
        编辑模式
    </button>

    <!-- JavaScript -->
    <script src="./assets/bootstrap.bundle.min.js"></script>
    <!-- GridStack JavaScript -->
    <script src="./assets/gridstack-all.js"></script>
    
    <script>
        let dashboards = [];
        let currentDashboard = null;
        let charts = [];
        let gridInstance = null; // 添加GridStack实例管理

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            loadDashboards();
            loadCharts();
        });

        // 加载仪表板列表
        async function loadDashboards() {
            try {
                const response = await fetch('/api/v0/dashboards');
                const data = await response.json();
                
                if (data.type === 'dashboard_list') {
                    dashboards = data.dashboards;
                    renderDashboardGrid();
                } else {
                    console.error('加载仪表板失败:', data.error);
                    showError('加载仪表板失败');
                }
            } catch (error) {
                console.error('加载仪表板失败:', error);
                showError('网络连接失败');
            }
        }

        // 加载图表列表
        async function loadCharts() {
            try {
                const response = await fetch('/api/v0/charts');
                const data = await response.json();
                
                if (data.type === 'chart_list') {
                    charts = data.charts;
                } else {
                    console.error('加载图表失败:', data.error);
                }
            } catch (error) {
                console.error('加载图表失败:', error);
            }
        }

        // 渲染仪表板网格
        function renderDashboardGrid() {
            const container = document.getElementById('dashboardGrid');
            
            if (dashboards.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-tachometer-alt"></i>
                        <h4>暂无仪表板</h4>
                        <p>您还没有创建任何仪表板。仪表板可以帮助您将多个图表组织在一起，形成完整的数据分析视图。</p>
                        <div class="mt-3">
                            <button class="btn btn-primary" onclick="switchToEditMode()">
                                <i class="fas fa-plus me-2"></i>创建第一个仪表板
                            </button>
                        </div>
                    </div>
                `;
                return;
            }

            container.innerHTML = dashboards.map(dashboard => `
                <div class="dashboard-card" onclick="loadDashboard('${dashboard.id}')" data-dashboard-id="${dashboard.id}">
                    <h5>${dashboard.name}</h5>
                    <p class="text-muted mb-2">${dashboard.description || '无描述'}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="fas fa-clock me-1"></i>
                            ${new Date(dashboard.created_at).toLocaleDateString()}
                        </small>
                        <small class="text-muted">
                            <i class="fas fa-chart-bar me-1"></i>
                            ${dashboard.charts && dashboard.charts.length > 0 ? dashboard.charts[0].count : 0} 个图表
                        </small>
                    </div>
                </div>
            `).join('');
        }

        // 加载仪表板
        async function loadDashboard(dashboardId) {
            try {
                const response = await fetch(`/api/v0/dashboards/${dashboardId}`);
                const data = await response.json();
                
                if (data.type === 'dashboard_detail') {
                    currentDashboard = data.dashboard;
                    renderDashboard();
                    
                    // 更新选中状态
                    document.querySelectorAll('.dashboard-card').forEach(card => {
                        card.classList.remove('active');
                    });
                    document.querySelector(`[data-dashboard-id="${dashboardId}"]`).classList.add('active');
                } else {
                    console.error('加载仪表板失败:', data.error);
                    showError('加载仪表板失败');
                }
            } catch (error) {
                console.error('加载仪表板失败:', error);
                showError('网络连接失败');
            }
        }

        // 渲染仪表板
        function renderDashboard() {
            if (!currentDashboard) return;

            // 显示仪表板内容
            document.getElementById('dashboardContent').style.display = 'block';
            
            // 更新标题和描述
            document.getElementById('dashboardTitle').textContent = currentDashboard.name;
            document.getElementById('dashboardDescription').textContent = currentDashboard.description || '无描述';

            // 渲染图表
            renderCharts();
        }

        // 渲染图表
        function renderCharts() {
            const container = document.getElementById('chartsGrid');
            
            console.log('渲染图表 - currentDashboard:', currentDashboard);
            
            // 销毁之前的GridStack实例
            if (gridInstance) {
                try {
                    gridInstance.destroy(false); // 不删除DOM元素
                } catch (e) {
                    console.warn('销毁GridStack实例失败:', e);
                }
                gridInstance = null;
            }
            
            if (!currentDashboard.charts || currentDashboard.charts.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-chart-bar"></i>
                        <h4>仪表板为空</h4>
                        <p>这个仪表板还没有添加任何图表。您可以切换到编辑模式来添加图表，或者前往聊天页面创建新的图表。</p>
                        <div class="mt-3">
                            <button class="btn btn-primary me-2" onclick="switchToEditMode()">
                                <i class="fas fa-edit me-2"></i>编辑仪表板
                            </button>
                            <button class="btn btn-outline-primary" onclick="window.location.href='/static/chat.html'">
                                <i class="fas fa-comments me-2"></i>创建图表
                            </button>
                        </div>
                    </div>
                `;
                return;
            }

            // 按位置排序图表
            const sortedCharts = currentDashboard.charts.sort((a, b) => {
                let posA, posB;
                try {
                    posA = typeof a.position === 'string' ? JSON.parse(a.position) : a.position;
                    posB = typeof b.position === 'string' ? JSON.parse(b.position) : b.position;
                } catch (e) {
                    console.warn('解析位置信息失败:', e);
                    posA = { x: 0, y: 0 };
                    posB = { x: 0, y: 0 };
                }
                if (posA.y !== posB.y) return posA.y - posB.y;
                return posA.x - posB.x;
            });

            // 清空容器并重置类名
            container.innerHTML = '';
            container.className = 'grid-stack';
            
            // 初始化新的GridStack实例
            gridInstance = GridStack.init({
                cellHeight: 80, // 与编辑模式一致
                margin: 10,
                column: 12, // 与编辑模式一致
                staticGrid: true, // 查看模式下禁用拖拽
                disableMove: true,
                disableResize: true,
                animate: true,
                minRow: 1,
                sizeToContent: false
            }, container);

            // 添加图表到GridStack
            sortedCharts.forEach((chart, index) => {
                // 解析位置信息
                let position;
                try {
                    if (chart.position) {
                        position = typeof chart.position === 'string' ? JSON.parse(chart.position) : chart.position;
                    } else {
                        position = {
                            x: chart.position_x || 0,
                            y: chart.position_y || 0,
                            width: chart.width || 6,
                            height: chart.height || 4
                        };
                    }
                } catch (e) {
                    position = { x: 0, y: 0, width: 6, height: 4 };
                }
                // 先 addWidget 创建空容器，再插入内容，避免 content 被当作纯文本
                const widgetEl = gridInstance.addWidget({
                    x: position.x || 0,
                    y: position.y || 0,
                    w: position.width || 6,
                    h: position.height || 4
                });
                if (widgetEl) {
                    widgetEl.querySelector('.grid-stack-item-content').innerHTML = `
                        <div class=\"chart-container\">
                            <div class=\"chart-title-container\" style=\"position: relative; display: flex; align-items: center; justify-content: space-between; padding: 5px 10px; background: #f8f9fa; border-bottom: 1px solid #dee2e6;\">
                                <div class=\"chart-title\" data-chart-id=\"${chart.id}\" style=\"flex: 1; cursor: pointer; padding: 2px 5px; border-radius: 3px;\">${chart.title}</div>
                                <div class=\"chart-actions\" style=\"display: flex; gap: 5px;\">
                                    <button class=\"btn btn-sm btn-outline-primary\" onclick=\"toggleFullscreen('chart-${chart.id}')\" title=\"全屏查看\" style=\"padding: 2px 6px; font-size: 12px;\">
                                        <i class=\"fas fa-expand\"></i>
                                    </button>
                                </div>
                            </div>
                            <div class=\"chart-container\" id=\"chart-${chart.id}\" style=\"height: calc(100% - 50px);\"></div>
                        </div>
                    `;
                }
            });

            // 延迟渲染图表以确保DOM已更新
            setTimeout(() => {
                sortedCharts.forEach(chart => {
                    renderChart(chart);
                });
            }, 100);
        }

        // 渲染单个图表
        function renderChart(chart) {
            const container = document.getElementById(`chart-${chart.id}`);
            if (!container) return;

            console.log('渲染图表详情:', chart);

            try {
                if (chart.chart_type === 'plotly') {
                    // chart_config/data_config 需解析为对象
                    let chartData = chart.chart_config || chart.data_config;
                    if (typeof chartData === 'string') {
                        // 第一次解析
                        let parsedData = JSON.parse(chartData);
                        // 如果结果还是字符串，再次解析
                        if (typeof parsedData === 'string') {
                            chartData = JSON.parse(parsedData);
                        } else {
                            chartData = parsedData;
                        }
                    }
                    // 获取容器的实际高度
                    const containerHeight = container.offsetHeight;
                    // 优化布局以适应查看模式
                    const layout = {
                        ...chartData.layout,
                        margin: { t: 20, r: 10, b: 30, l: 30 },
                        showlegend: true,
                        legend: {
                            orientation: 'h',
                            x: 0.5,
                            xanchor: 'center',
                            y: -0.1
                        },
                        font: {
                            size: 11
                        },
                        autosize: false,
                        width: container.offsetWidth,
                        height: containerHeight > 0 ? containerHeight : 300
                    };
                    Plotly.newPlot(container, chartData.data, layout, {
                        responsive: true,
                        displayModeBar: true,
                        modeBarButtonsToRemove: ['pan2d', 'lasso2d', 'select2d'],
                        displaylogo: false,
                        scrollZoom: false,
                        doubleClick: false,
                        showTips: false,
                        staticPlot: false
                    }).then(() => {
                        Plotly.Plots.resize(container);
                        const plotlyDiv = container.querySelector('.js-plotly-plot');
                        if (plotlyDiv) {
                            plotlyDiv.style.overflow = 'hidden';
                            plotlyDiv.style.overflowX = 'hidden';
                            plotlyDiv.style.overflowY = 'hidden';
                        }
                    });
                } else if (chart.chart_type === 'table') {
                    let tableData;
                    const configData = chart.chart_config || chart.data_config;
                    if (typeof configData === 'string') {
                        // 第一次解析
                        let parsedData = JSON.parse(configData);
                        // 如果结果还是字符串，再次解析
                        if (typeof parsedData === 'string') {
                            tableData = JSON.parse(parsedData);
                        } else {
                            tableData = parsedData;
                        }
                    } else {
                        tableData = configData;
                    }
                    // 处理HTML转义问题
                    let htmlContent = tableData;
                    if (typeof htmlContent === 'string') {
                        // 解码HTML实体
                        const tempDiv = document.createElement('div');
                        tempDiv.innerHTML = htmlContent;
                        htmlContent = tempDiv.innerHTML;
                    }
                    container.innerHTML = `
                        <div style="overflow: auto; height: 100%; padding: 10px; border: 1px solid #dee2e6; border-radius: 8px;">
                            ${htmlContent}
                        </div>
                    `;
                }
            } catch (error) {
                console.error('渲染图表失败:', error, chart);
                container.innerHTML = `
                    <div class="d-flex align-items-center justify-content-center h-100 text-muted">
                        <div class="text-center">
                            <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                            <div>图表渲染失败</div>
                            <small>${error.message}</small>
                        </div>
                    </div>
                `;
            }
        }

        // 切换到编辑模式
        function switchToEditMode() {
            window.location.href = '/dashboard.html';
        }

        // 全屏显示图表
        function toggleFullscreen(chartId) {
            const chartContainer = document.getElementById(chartId);
            if (!chartContainer) return;

            const existingFullscreen = document.querySelector('.fullscreen-chart');
            if (existingFullscreen) {
                existingFullscreen.remove();
                return;
            }

            const fullscreenDiv = document.createElement('div');
            fullscreenDiv.className = 'fullscreen-chart';
            fullscreenDiv.innerHTML = `
                <button class="close-btn" onclick="this.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
                <div id="${chartId}-fullscreen" style="width: 100%; height: calc(100% - 4rem);"></div>
            `;
            
            document.body.appendChild(fullscreenDiv);

            // 重新渲染图表到全屏容器
            const chartData = chartContainer.querySelector('.js-plotly-plot');
            if (chartData) {
                const fullscreenContainer = document.getElementById(`${chartId}-fullscreen`);
                Plotly.newPlot(fullscreenContainer, chartData.data, chartData.layout, {
                    responsive: true,
                    displayModeBar: true,
                    displaylogo: false
                });
            }
        }

        // 显示错误信息
        function showError(message) {
            const container = document.getElementById('dashboardGrid');
            container.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h5>加载失败</h5>
                    <p>${message}</p>
                    <div class="mt-3">
                        <button class="btn btn-danger me-2" onclick="location.reload()">
                            <i class="fas fa-redo me-2"></i>重新加载
                        </button>
                        <button class="btn btn-outline-secondary" onclick="window.location.href='/static/dashboard.html'">
                            <i class="fas fa-edit me-2"></i>编辑模式
                        </button>
                    </div>
                </div>
            `;
        }

        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const fullscreen = document.querySelector('.fullscreen-chart');
                if (fullscreen) {
                    fullscreen.remove();
                }
            }
        });

        // 窗口大小变化时重新调整图表尺寸
        window.addEventListener('resize', function() {
            if (currentDashboard && currentDashboard.charts) {
                currentDashboard.charts.forEach(chart => {
                    const container = document.getElementById(`chart-${chart.id}`);
                    if (container && container.querySelector('.js-plotly-plot')) {
                        Plotly.Plots.resize(container);
                    }
                });
            }
        });
    </script>
</body>
</html>
